package com.pda.yuanjing.pages.custombill.add;

import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.AddCBillBeanIn;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.SCBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.database.InStore;
import com.pda.yuanjing.dialog.dealer.DealerDialog;
import com.pda.yuanjing.dialog.gys.GYSDialog;
import com.pda.yuanjing.dialog.product.ProducttDialog;
import com.pda.yuanjing.dialog.store.StoretDialog;
import com.pda.yuanjing.pages.inbilln.add.ProductAdapter;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.DateUtils;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BillAddActivity extends BaseActivity<AddBillModel, AddBillView, AddBillPresent> implements AddBillView {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvbill)
    EditText tvbill;
    @BindView(R.id.tvproduct)
    TextView tvproduct;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.edcode)
    EditText edcode;
    @BindView(R.id.logine)
    Button logine;
    @BindView(R.id.ll3)
    LinearLayout ll3;
    @BindView(R.id.listview)
    SwipeMenuListView listview;
    @BindView(R.id.tvb)
    TextView tvb;
    @BindView(R.id.tvstore)
    TextView tvstore;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.tvkf)
    TextView tvkf;
    @BindView(R.id.ll6)
    LinearLayout ll6;
    @BindView(R.id.tvgys)
    TextView tvgys;
    @BindView(R.id.ll7)
    LinearLayout ll7;
    @BindView(R.id.tvjxs)
    TextView tvjxs;
    @BindView(R.id.ll8)
    LinearLayout ll8;
    @BindView(R.id.tvbatch)
    EditText tvbatch;

    private String TAG = "BillAddActivity";
    JDBeanNewOut.DataBean dataBean = null;
    ProducttDialog productDialog;
    StoretDialog storeDialog;
    DealerDialog dealerDialog;
    GYSDialog gysDialog;
    String pstr = "";
    int cnum = 0;
    ProductAdapter productAdapter = null;
    List<InStore> list = new ArrayList<>();
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    String sstr = "";
    String dstr = "";
    String gstr = "";

    protected void initdata() {
        dataBean = (JDBeanNewOut.DataBean) getIntent().getSerializableExtra(PDApp.process);
        tvTitle.setText(dataBean.getJieDianName() + " " + SharedPreferencesManger.getRealName());
        tvbill.setText(dataBean.getProcessID() + DateUtils.stampToDateTime(new Date().getTime()));
        View headView = getLayoutInflater().inflate(R.layout.head_iscanf, null);
        listview.addHeaderView(headView, null, false);
        listview.setHeaderDividersEnabled(false);
        productAdapter = new ProductAdapter(this, list);
        listview.setAdapter(productAdapter);
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                deleteItem.setWidth(100);
                deleteItem.setTitle("删除");
                deleteItem.setTitleSize(16);
                deleteItem.setTitleColor(Color.WHITE);
                deleteItem.setBackground(R.color.red);
                menu.addMenuItem(deleteItem);
            }
        };
        listview.setMenuCreator(creator);
        listview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        list.remove(position);
                        productAdapter = new ProductAdapter(BillAddActivity.this, list);
                        listview.setAdapter(productAdapter);
                        break;
                }
                return false;
            }
        });

        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        String ss = StringProcess.codeMat(string);
                        if (!PDApp.scanfp) {
                            getRes("1", ss);
                            return;
                        }
                        if (!PDApp.scanfs) {
                            getRes("2", ss);
                            return;
                        }
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcbill);
        ButterKnife.bind(this);
        initdata();
        if (dataBean.getBillType().equals("600")) {
            ll7.setVisibility(View.VISIBLE);
        } else if (dataBean.getBillType().equals("700")) {
            ll8.setVisibility(View.VISIBLE);
        } else if (dataBean.getBillType().equals("800")) {
            ll8.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
    }

    @OnClick({R.id.iv_title_left, R.id.logine, R.id.tv_right, R.id.tvproduct, R.id.tvgys, R.id.tvjxs})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvgys:
                gysDialog = new GYSDialog(mContext, R.style.CommentDialog, new GYSDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1) {
                        tvgys.setText(str);
                        gstr = str1;
                        gysDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp3 = gysDialog.getWindow().getAttributes();
                lp3.gravity = Gravity.CENTER;
                gysDialog.show();
                break;
            case R.id.tvjxs:
                dealerDialog = new DealerDialog(mContext, R.style.CommentDialog, new DealerDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1) {
                        tvjxs.setText(str);
                        dstr = str1;
                        dealerDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp2 = dealerDialog.getWindow().getAttributes();
                lp2.gravity = Gravity.CENTER;
                dealerDialog.show();
                break;
            case R.id.logine:
                if (tvbill.getText().toString().length() == 0) {
                    showMsg("请填写单号");
                    return;
                }
                if (edcode.getText().toString().length() == 0) {
                    showMsg("请填写数量");
                    return;
                }
                if (Integer.parseInt(edcode.getText().toString()) <= 0) {
                    showMsg("应扫数必须大于0");
                    return;
                }
                if (pstr.length() == 0) {
                    showMsg("请填写产品");
                    return;
                }
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getProductID().equals(pstr)) {
                        showMsg("请填选择不同产品");
                        return;
                    }
                }
                InStore inStore = new InStore();
                inStore.setBillID(tvbill.getText().toString());
                inStore.setBillCode(tvbill.getText().toString());
                inStore.setCreateTime(DateUtils.stampToDate(new Date().getTime()));
                inStore.setDesStoreID(SharedPreferencesManger.getStoreID());
                inStore.setDesStoreName(SharedPreferencesManger.getStoreName());
                inStore.setProductID(pstr);
                inStore.setProductName(tvproduct.getText().toString());
                inStore.setCaseBoxNum(cnum);
                inStore.setYnum(Integer.parseInt(edcode.getText().toString()));
                inStore.setSnum(0);
                inStore.setBillListID(pstr + "-" + DateUtils.stampToDateTime(new Date().getTime()));
                list.add(inStore);
                productAdapter.notifyDataSetChanged();
                pstr = "";
                tvproduct.setText("");
                edcode.setText("");
                break;
            case R.id.tv_right:
                if (tvbill.getText().toString().length() == 0) {
                    showMsg("请填写单号");
                    return;
                }
//                if (tvbatch.getText().toString().length() == 0) {
//                    showMsg("请填写批次");
//                    return;
//                }
                if (list.size() == 0) {
                    showMsg("当前订单无任何产品信息");
                    return;
                }
                if (dataBean.getBillType().equals("600") && gstr.equals("")) {
                    showMsg("请选择供应商");
                    return;
                }
                if (dataBean.getBillType().equals("700") && dstr.equals("")) {
                    showMsg("请选择经销商");
                    return;
                }
                if (dataBean.getBillType().equals("800") && dstr.equals("")) {
                    showMsg("请选择经销商");
                    return;
                }
                AddCBillBeanIn addCBillBeanIn = new AddCBillBeanIn();
                addCBillBeanIn.setCid(SharedPreferencesManger.getCid());
                addCBillBeanIn.setAction("SY_AddBatch");
                addCBillBeanIn.setUserID(SharedPreferencesManger.getUid());
                addCBillBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
                addCBillBeanIn.setBillCode(tvbill.getText().toString());
                addCBillBeanIn.setJieDianName(dataBean.getJieDianName());
                addCBillBeanIn.setProcessID(dataBean.getProcessID());
                addCBillBeanIn.setBillType(dataBean.getBillType());
                addCBillBeanIn.setGongYingShangID(gstr);
                addCBillBeanIn.setStoreIDIn(sstr);
                addCBillBeanIn.setDealerID(dstr);
                addCBillBeanIn.setBatch(tvbatch.getText().toString());
                for (int i = 0; i < list.size(); i++) {
                    AddCBillBeanIn.DataBean dataBean = new AddCBillBeanIn.DataBean();
                    dataBean.setPlanNums(list.get(i).getYnum());
                    dataBean.setProductID(list.get(i).getProductID());
                    dataBean.setProductName(list.get(i).getProductName());
                    addCBillBeanIn.getListProduct().add(dataBean);
                }
                presenter.addList(addCBillBeanIn);
                break;
            case R.id.tvproduct:
                tvproduct.setEnabled(false);
                presenter.initBase(dataBean.getProcessID(), dataBean.getJieDianName());
                productDialog = new ProducttDialog(mContext, R.style.CommentDialog, new ProducttDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1, int num) {
                        tvproduct.setText(str);
                        pstr = str1;
                        cnum = num;
                        productDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp = productDialog.getWindow().getAttributes();
                lp.gravity = Gravity.CENTER;
                productDialog.show();
                tvproduct.setEnabled(true);
                break;
        }
    }

    @Override
    public void tip(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (str.length() == 0) {
                    showMsg("订单添加完成");
                    finish();
                } else {
                    showMsg(str);
                }
            }
        });
    }

    @Override
    public AddBillModel createModel() {
        return new AddBillModelImpl(this);
    }

    @Override
    public AddBillView createView() {
        return this;
    }

    @Override
    public AddBillPresent createPresenter() {
        return new AddBillPresent();
    }

    public void getRes(final String id, String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_QueryProdcutStoreByCode");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setBaseType(id);
            jieDianBeanIn.setCodecc(code);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            SCBeanOut scBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), SCBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (id.equals("1")) {
                                        productDialog.dismiss();
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到产品信息");
                                        } else {
                                            boolean flag = true;
                                            for (int i = 0; i < PDApp.productBeanOutt.getData().size(); i++) {
                                                if (PDApp.productBeanOutt.getData().get(i).getId().equals(scBeanOut.getData().getIdStr())) {
                                                    flag = false;
                                                    break;
                                                }
                                            }
                                            if (flag) {
                                                showMsg("未匹配到产品信息");
                                                return;
                                            }
                                            tvproduct.setText(scBeanOut.getData().getNameStr());
                                            pstr = scBeanOut.getData().getIdStr();
                                        }
                                    } else if (id.equals("2")) {
                                        storeDialog.dismiss();
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到库房信息");
                                        } else {
                                            tvkf.setText(scBeanOut.getData().getNameStr());
                                            sstr = scBeanOut.getData().getIdStr();
                                        }
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }
}
